package com.yswy.backstage.serviceApi.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.backstage.dto.api.AppEventCallback;
import com.yswy.backstage.dto.api.TgCallBackIdReids;
import com.yswy.backstage.dto.api.UserDeviceInfo;
import com.yswy.backstage.service.TgEventEnumsService;
import com.yswy.backstage.service.TgEventService;
import com.yswy.backstage.serviceApi.ApiTgCallBackJlIdService;
import com.yswy.backstage.serviceApi.ApiTgCallBackLoglService;
import com.yswy.backstage.serviceApi.ApiTgChannelService;
import com.yswy.backstage.utils.BackStringUtils;
import com.yswy.common.enums.TfPlatformEnums;
import com.yswy.common.runnableUtil.Pooled;
import com.yswy.common.utils.HttpUtil;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.entity.tf.*;
import com.yswy.domain.mapper.tf.TgCallBackJlIdMapper;
import com.yswy.domain.vo.dto.TgDevice;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ApiTgCallBackJlIdServiceImpl extends ServiceImpl<TgCallBackJlIdMapper, TgCallBackJlId>
        implements ApiTgCallBackJlIdService {
    @Autowired
    private  RedisUtil redisUtil ;
    @Autowired
    private  ApiTgChannelService apiTgChannelService ;
    @Autowired
    private  ApiTgCallBackLoglService apiTgCallBackLoglService ;
    @Autowired
    private  TgEventService tgEventService ;
    @Override
    @Pooled(executor = "tgCallBackIdInp", poolOverAct = Pooled.PoolOverAct.NEW_THREAD)
    public void addTgCallBackJlId(String channel ,String packChannel ,Long projectId, HttpServletRequest request , Integer activeType) {
//        long begin = System.currentTimeMillis();
        TgDevice tgDevice = new TgDevice(request);
        if (StringUtils.isEmpty(tgDevice.getCALLBACK_PARAM()))return;
        if (StringUtils.isEmpty(channel))return;
        TgCallBackJlId tgCallBackJlId = new TgCallBackJlId(channel ,packChannel ,projectId , tgDevice , activeType);
        String isCacheTgBack = RedisConstants.isCacheTgBack_jlyq+tgCallBackJlId.getCallbackparamCrc();
        if (redisUtil.hasKey(isCacheTgBack)){
            return;
        }

        Integer count = count(new LambdaQueryWrapper<TgCallBackJlId>()
                .eq(TgCallBackJlId::getCallbackparamCrc ,tgCallBackJlId.getCallbackparamCrc()));
        if (count<=0){
            save(tgCallBackJlId);
            redisUtil.setForObjectTimeCustom(isCacheTgBack, tgCallBackJlId, 5, TimeUnit.MINUTES);
            TgEvent tgEvent = tgEventService.getTgEventByChannel(channel);
            if (tgEvent == null){
                log.info("巨量渠道"+channel+"未配置参数");
                return;
            }
            List<TgEventChild> tgEventChilds = tgEvent.getTgEventChildrens();
            if (tgEventChilds.size()<=0){
                log.info("巨量渠道"+channel+"未配置参数");
                return;
            }
            for (TgEventChild tc:tgEventChilds) {
                String oaidCache = null;
                String ipCache = null;
                if (StringUtils.isNotEmpty(tgCallBackJlId.getOaid())){
                    oaidCache = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_oaid_jlyq
                    ,tgCallBackJlId.getOaid() ,packChannel , projectId ,  tc.getTriggerNode());
                }
                if (StringUtils.isNotEmpty(tgCallBackJlId.getChannelip())){
                    ipCache =  BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_ip_jlyq
                            ,tgCallBackJlId.getChannelip() ,packChannel , projectId ,  tc.getTriggerNode());
                }

                if (StringUtils.isNotEmpty(oaidCache)){
                    redisUtil.setForObjectTimeCustom(oaidCache, tgCallBackJlId, tc.getCacheTime(), TimeUnit.DAYS);
                }
                if (StringUtils.isNotEmpty(ipCache)){
                    redisUtil.setForObjectTimeCustom(ipCache, tgCallBackJlId, tc.getCacheTime(), TimeUnit.DAYS);
                }
            }

        }
//        long end = System.currentTimeMillis();
//        System.out.println("耗时：tg/handleCallback："+ (end-begin));
    }

    @Override
    public TgCallBackLog callBack(AppEventCallback appEventCallback , TgCallBackIdReids tgCallBackIdReids , TgEventEnums tgEventEnums) {
        TgCallBackJlId tgCallBackJlId = tgCallBackIdReids.getTgCallBackJlId();
        String oaidMd5 = tgCallBackIdReids.getOaidCache();
        String modelIpMd5 =tgCallBackIdReids.getIpCache();
        Integer price = appEventCallback.getPrice();
        UserDeviceInfo userDeviceInfo = appEventCallback.getUserDeviceInfo();
        Boolean isDeduction = false ;
        if (tgEventEnums.getIsBuckle() == 1){
            isDeduction = apiTgChannelService.isDeduction(tgCallBackJlId.getChannel() , price);
        }
        //回传登录Key  active
        String eventKey =tgEventEnums.getEventKey();
        TgCallBackLog tgCallBackLog = new TgCallBackLog();
        tgCallBackLog.setTfPlatform(TfPlatformEnums.JLYQ.toString());
        tgCallBackLog.setUserId(userDeviceInfo.getUserId());
        tgCallBackLog.setBackJlId(tgCallBackJlId.getId());
        tgCallBackLog.setTgEventEnumsId(tgEventEnums.getId());
        tgCallBackLog.setIsDeduction(isDeduction);
        //回传
        if (!isDeduction){
            String body = callBack(tgCallBackJlId ,eventKey );
            tgCallBackLog.setCallbackBody(body);
        }
        redisUtil.delete(oaidMd5);
        redisUtil.delete(modelIpMd5);
        apiTgCallBackLoglService.save(tgCallBackLog);
        return tgCallBackLog;
    }


    public static String callBack(TgCallBackJlId tgCallBackJlId , String eventEype){
        JSONObject ad = new JSONObject();
        ad.put("callback" ,tgCallBackJlId.getCallbackparam());
        JSONObject context = new JSONObject();
        context.put("ad", ad);
        JSONObject map = new JSONObject();
        map.put("event_type" , eventEype) ;
        map.put("context" , context) ;
        map.put("timestamp" , new Date().getTime()) ;
        String body = HttpUtil.doPost("https://analytics.oceanengine.com/api/v2/conversion"
                , map);
        log.info("巨量引擎联调 , 响应："+body + " callback: "+tgCallBackJlId.getCallbackparammd5()+ " eventEype: "+eventEype);
        return body ;
    }


    public static void main(String[] args) {
//        TgCallBackJlId tgCallBackId = new TgCallBackJlId();
//        tgCallBackId.setCallbackparam("B.DGUxYHChX0vKpyJ4HN9xDBV5C9Dk6QdBm2rR27WrkqZwqNvazpKe8r1YRQkkfP67m69b8QVBgmJKjv7MLzdjh1VqSzB9G5aQnnvtzczAn37q1uqkidBTfwlqRYc94beN366lKy7SZG0dMJqyO7oddq");
//
//        callBack(tgCallBackId , "game_addiction");
        String b = "ELS-AN00118.113.4.235";
        String s = "ELS-AN00118.113.4.235";
        System.out.println(b.replaceAll("\\s" , ""));
        System.out.println(s.replaceAll("\\s" , ""));
        System.out.println(Md5Utils.getMD5(b.replaceAll("\\s" , ""), "utf8"));
        System.out.println(Md5Utils.getMD5(s.replaceAll("\\s" , ""), "utf8"));

    }
}

